package com.cmict.data.form.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import com.cmict.data.form.api.entity.dataobject.SysFormDO;
import com.cmict.data.form.api.entity.dataobject.SysFormItemRespVO;
import com.cmict.data.form.api.entity.vo.SysFormReqVO;
import com.cmict.data.form.api.entity.vo.SysFormVo;
import com.cmict.data.form.api.service.SysFormService;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.alibaba.fastjson.JSONArray;
import com.cmict.data.framework.common.pojo.PageResult;
import com.cmict.data.system.api.permission.dto.MenuDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.cmict.data.framework.common.pojo.CommonResult.error;
import static com.cmict.data.framework.common.pojo.CommonResult.success;

/**
 * 表单表
 *
 * @author
 * @date 2022-03-21 11:37:08
 */
@RestController
@Validated
@RequestMapping("/form/sys" )
@Api(value = "sysform", tags = "表单表管理")
public class SysFormController {

    @Resource
    private SysFormService sysFormService;

    /**
     * 表单设计列表分页查询
     * @param reqVO 表单表
     * @return
     */
    @ApiOperation(value = "表单设计列表分页查询", notes = "表单设计列表分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@ss.hasPermission('form:sysform:query')")
    public CommonResult<PageResult<SysFormItemRespVO>> getSysFormPage(SysFormReqVO reqVO) {
        return success(sysFormService.getFormPage(reqVO));
    }

    /**
     * 表单设计列表启用的
     * @param
     * @return
     */
    @ApiOperation(value = "表单设计列表分页查询", notes = "表单设计列表分页查询")
    @GetMapping("/pageIsenable" )
    public CommonResult<PageResult<SysFormItemRespVO>> pageIsenable(SysFormReqVO reqVO) {
        return success(sysFormService.getSysFormPageIsenable(reqVO));
    }


    /**
     * 表单发布列表分页查询
     * @param reqVO 表单表
     * @return
     */
    @ApiOperation(value = "表单发布列表分页查询", notes = "表单发布列表分页查询")
    @GetMapping("/pageRelease" )
    @PreAuthorize("@ss.hasPermission('form:sysform:pubquery')")
    public CommonResult<PageResult<SysFormItemRespVO>> getFormPageRelease(SysFormReqVO reqVO) {
        return success(sysFormService.getFormPageRelease(reqVO));
    }

    /**
     * 未发布表单分页列表
     * @param reqVO 表单表
     * @return
     */
    @ApiOperation(value = "未发布表单分页列表", notes = "未发布表单分页列表")
    @GetMapping("/pageNoRelease" )
    @PreAuthorize("@ss.hasPermission('form:sysform:pubquery')")
    public CommonResult<PageResult<SysFormItemRespVO>> getFormPageNoRelease(SysFormReqVO reqVO) {
        return success(sysFormService.getFormPageNoRelease(reqVO));
    }

    /**
     * 获取已发布表单，数据源下拉使用
     * @return
     */
    @ApiOperation(value = "获取已发布表单", notes = "获取已发布表单")
    @GetMapping("/selectListRelease" )
    public CommonResult<List<SysFormDO>> selectListRelease() {
        return success(sysFormService.selectListRelease());
    }
    /**
     * 获取已发布表单，数据源下拉使用
     * @return
     */
    @ApiOperation(value = "自动编码使用 获取已发布表单", notes = "自动编码使用 获取已发布表单")
    @GetMapping("/selectListReleaseByEncode" )
    public CommonResult<List<SysFormDO>> selectListReleaseByEncode(@RequestParam("tableName") String tableName) {
        return success(sysFormService.selectListReleaseByEncode(tableName));
    }
    @ApiOperation(value = "自动编码 获取表中的所有字段", notes = "自动编码 获取表中的所有字段")
    @GetMapping(value = "/getFieldNameList")
    public CommonResult<List<Map<String,Object>>> getFieldNameList(@RequestParam("tableName") String tableName)  {
        return success(sysFormService.getFieldNameList(tableName));
    }

    /**
     * 获取全部表单，数据源下拉使用
     * @return
     */
    @ApiOperation(value = "获取全部表单", notes = "获取全部表单")
    @GetMapping("/selectListAll" )
    public CommonResult<List<SysFormDO>> selectListAll() {
        return success(sysFormService.selectListAll());
    }

    /**
     * 通过id查询表单表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public CommonResult getById(@PathVariable("id" ) Long id) throws InvocationTargetException, IllegalAccessException {
        List<SysFormDO> sysFormDOList = sysFormService.getChildSysFormByIds(id);
        JSONArray json = new JSONArray();
        SysFormDO sysform = sysFormService.getSysForm(id);
        SysFormVo sysFormVo = new SysFormVo();
        BeanUtils.copyProperties(sysform,sysFormVo);
        if(ObjectUtil.isNotEmpty(sysFormDOList)){
            for (int i = 0; i <sysFormDOList.size() ; i++) {
                json.add(sysFormDOList.get(i));
            }
        }
        sysFormVo.setChildFormJsonData(json.toString());
        return success(sysFormVo);
    }

    /**
     * 通过id查询表单表
     * @param id id
     * @return R
     */
    /*@ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    public CommonResult getById(@PathVariable("id" ) Long id) throws InvocationTargetException, IllegalAccessException {
        List<SysFormDO> sysFormDOList = sysFormService.getChildSysFormByIds(id);
        if(ObjectUtil.isNotEmpty(sysFormDOList)){
            JSONArray json = new JSONArray();
            for (int i = 0; i <sysFormDOList.size() ; i++) {
                json.add(sysFormDOList.get(i));
            }
            SysFormDO sysform = sysFormService.getSysForm(id);
            SysFormVo sysFormVo = new SysFormVo();
            BeanUtils.copyProperties(sysform,sysFormVo);
            sysFormVo.setChildFormJsonData(json.toString());
            return success(sysFormVo);
        }
        return success(sysFormService.getSysForm(id));
    }*/

    /**
     * 新增表单表
     * @param formDO 表单表
     * @return R
     */
    @ApiOperation(value = "新增表单表", notes = "新增表单表")
    @PostMapping
    @PreAuthorize("@ss.hasPermission('form:sysform:create')")
    public CommonResult save(@RequestBody SysFormDO formDO) {
        SysFormDO sysFormDO = sysFormService.selectOne(formDO.getTableName());
        if(ObjectUtil.isNotEmpty(sysFormDO)){
            return success("创建失败,表单已存在");
        }
        return success(sysFormService.createForm(formDO));
    }

    /**
     * 新增表单表
     * @param formDOList 批量新增表单表
     * @return R
     */
    @ApiOperation(value = "批量新增表单表", notes = "批量新增表单表")
    @PostMapping("/savelist" )
    public CommonResult saveList(@RequestBody List<SysFormDO> formDOList) {
        List<Long> ids = new ArrayList<>();
        for(SysFormDO sysFormDO : formDOList){
            SysFormDO sysForm = sysFormService.selectOneByTableName(sysFormDO.getTableName());
            if(ObjectUtil.isNotEmpty(sysForm)){
                return success("创建失败,表单已存在");
            }
            Long id = sysFormService.createForm(sysFormDO);
            ids.add(id);
        }
        return success("创建成功",ids);
    }

    /**
     * 修改表单表
     * @param formDO 表单表
     * @return R
     */
    @ApiOperation(value = "修改表单表", notes = "修改表单表")
    @PostMapping("/edit" )
    @PreAuthorize("@ss.hasPermission('form:sysform:update')")
    public CommonResult updateById(@RequestBody SysFormDO formDO) {
        SysFormDO sysForm = sysFormService.selectOneByTableName(formDO.getTableName());
        if(ObjectUtil.isNotEmpty(sysForm) && !(String.valueOf(sysForm.getId()).equals(String.valueOf(formDO.getId())))){
            return success("更新失败,表单已存在");
        }
        sysFormService.updateForm(formDO);
        return success(true);
    }

    /**
     * 批量修改表单表
     * @param formDOList 批量表单表
     * @return R
     */
    @ApiOperation(value = "批量修改表单表", notes = "批量修改表单表")
    @PostMapping("/editlist" )
    public CommonResult editList(@RequestBody List<SysFormDO> formDOList) {
        for (int i = 0; i <formDOList.size() ; i++) {
            SysFormDO sysForm = sysFormService.selectOneByTableName(formDOList.get(i).getTableName());
            if(ObjectUtil.isNotEmpty(sysForm)){
                sysFormService.updateForm(formDOList.get(i));
            }else{
                return error(500,"修改失败,表单不存在");
            }
        }
        return success(true);
    }

    /**
     * 表单发布
     * @param formDO 表单表
     * @return R
     */
    @ApiOperation(value = "表单发布", notes = "表单发布")
    @PostMapping("/publish" )
    @PreAuthorize("@ss.hasPermission('form:sysform:pubcreate')")
    public CommonResult publish(@RequestBody SysFormDO formDO) {
        sysFormService.updateForm(formDO);
        return success(true);
    }

    /**
     * 通过id删除表单表(逻辑删除)
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除表单表", notes = "通过id删除表单表")
    @GetMapping("/delete/{id}" )
    @PreAuthorize("@ss.hasPermission('form:sysform:delete')")
    public CommonResult removeById(@PathVariable Long id) {
        if(sysFormService.deleteSysForm(id)){
            return success(true);
        }
        return error(999,"该表单已被引用！");
    }

    /**
     * 通过id删除子表单集合(物理删除)
     * @param tableNameList id
     * @return R
     */
    @ApiOperation(value = "通过id删除子表单集合", notes = "通过id删除子表单集合")
    @PostMapping("/deleteChildList" )
    @PreAuthorize("@ss.hasPermission('form:sysform:delete')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult removeByIdChildList(@RequestBody String[] tableNameList) {
        if(ObjectUtil.isNotEmpty(tableNameList)){
            for (String tableName: tableNameList) {
                if(!sysFormService.deleteSysFormChild(tableName)){
                    return error(999,tableName+" 表单删除失败，请检查是否已被引用！");
                }
            }
        }
        return success(true);
    }

    /**
     * 通过id删除子表单表(物理删除)
     * @param tableName id
     * @return R
     */
    @ApiOperation(value = "通过id删除子表单表", notes = "通过id删除子表单表")
    @GetMapping("/deleteChild/{tableName}" )
    @PreAuthorize("@ss.hasPermission('form:sysform:delete')")
    public CommonResult removeByIdChild(@PathVariable String tableName) {
        if(sysFormService.deleteSysFormChild(tableName)){
            return success(true);
        }
        return error(999,"该表单已被引用！");
    }

    /**
     * 通过id批量删除表单表(逻辑删除)
     * @param ids ids
     */
    @ApiOperation(value = "通过id批量删除表单表", notes = "通过id批量删除表单表")
    @PostMapping("/delete" )
    @PreAuthorize("@ss.hasPermission('form:sysform:delete')")
    public CommonResult batchRemove(@RequestBody Collection<Long> ids) {
        String result = sysFormService.batchDeleteSysForm(ids);
        if("所选数据删除失败！".equals(result)){
            return error(999,result);
        }else{
            return success(result);
        }
    }

    /**
     * 通过id批量取消引用
     * @param ids ids
     */
    @ApiOperation(value = "通过id批量取消引用", notes = "通过id批量取消引用")
    @PostMapping("/noReleaseBatch" )
    @PreAuthorize("@ss.hasPermission('form:sysform:pubdelete')")
    public CommonResult noReleaseBatch(@RequestBody Collection<Long> ids) {
        String result = sysFormService.noReleaseBatch(ids);
        if("所选数据删除失败！".equals(result)){
            return error(999,result);
        }else{
            return success(result);
        }
    }

    /**
     * 启用表单
     * @param id id
     * @return R
     */
    @ApiOperation(value = "启用表单", notes = "启用表单")
    @GetMapping("/enable/{id}" )
    @PreAuthorize("@ss.hasPermission('form:sysform:update')")
    public CommonResult enableById(@PathVariable Long id) {
        return success(sysFormService.enable(id));
    }

    /**
     * 禁用表单
     * @param id id
     * @return R
     */
    @ApiOperation(value = "禁用表单", notes = "禁用表单")
    @GetMapping("/disable/{id}" )
    @PreAuthorize("@ss.hasPermission('form:sysform:update')")
    public CommonResult disableById(@PathVariable Long id) {
        return success(sysFormService.disable(id));
    }

    /**
     * 取消引用
     * @param id id
     * @return R
     */
    @ApiOperation(value = "取消引用", notes = "取消引用")
    @GetMapping("/noRelease/{id}" )
    @PreAuthorize("@ss.hasPermission('form:sysform:update')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult noRelease(@PathVariable Long id) {
        return success(sysFormService.noRelease(id));
    }

    /**
     * 表单名获取表单
     * @param formName formName·
     * @return R
     */
    @ApiOperation(value = "表名获取表单", notes = "表名获取表单")
    @GetMapping("/getByFormName/{formName}" )
    public CommonResult getByTableName(@PathVariable String formName) {
        return success(sysFormService.selectOne(formName));
    }

    /**
     * 获取当前表菜单
     * @param tableName tableName·
     * @return R
     */
    @ApiOperation(value = "获取当前表菜单", notes = "获取当前表菜单")
    @GetMapping("/getByFormMenu" )
    public CommonResult getByFormMenu(@PathVariable String tableName) {
        return success(sysFormService.getByFormMenu(tableName));
    }
}
